package org.example.config;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import dev.langchain4j.service.V;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;
import java.util.Map;

@Configuration
public class RedisConfig {

    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    @Value("${spring.data.redis.host}")
    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    @Value("${spring.data.redis.port}")
    public void setPort(int port) {
        this.port = port;
    }

    @Bean
    public RedisTemplate<String, Map<String, List<String>>> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Map<String, List<String>>> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 配置 Jackson 序列化器
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, // 为非 final 类型的类添加类型信息
                JsonTypeInfo.As.PROPERTY
        );
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 设置 Key 的序列化器
        template.setKeySerializer(new StringRedisSerializer());

        // 设置 Value 的序列化器
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        // 设置 Hash Key 的序列化器
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置 Hash Value 的序列化器
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }


}